import ryu.app.simple_switch_13
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER, set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ipv4
from ryu.lib.packet import tcp
from ryu.lib.packet import ether_types
from ryu.ofproto import ether

# Define the IP and MAC addresses for the client, server1, and server2
client = {'ip': '10.0.1.5', 'mac': '00:00:00:00:00:03'}
server1 = {'ip': '10.0.1.2', 'mac': '00:00:00:00:00:01'}
server2 = {'ip': '10.0.1.3', 'mac': '00:00:00:00:00:02'}

class TrafficRedirectionApp(ryu.app.simple_switch_13.SimpleSwitch13):
    """
    Custom Ryu application for rerouting traffic based on initial TCP SYN packet.
    """

    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(TrafficRedirectionApp, self).__init__(*args, **kwargs)
        self.mac_to_port = {}

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        """
        Handle switch features event.
        """
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # Match all traffic and send it to the controller
        match_all = parser.OFPMatch()
        actions_all = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match_all, actions_all)

    def add_flow(self, datapath, priority, match, actions, buffer_id=None):
        """
        Add a flow entry to the switch.
        """
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # Create flow entry
        inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
        if buffer_id:
            mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id, priority=priority, match=match,
                                    instructions=inst)
        else:
            mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                    match=match, instructions=inst)
        datapath.send_msg(mod)

    def add_flow1(self, datapath, priority, match, actions, buffer_id=None):
        """
        Add a flow entry to the switch with an idle timeout of 5 seconds.
        """
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # Create flow entry with an idle timeout of 5 seconds
        inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
        if buffer_id:
            mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id, priority=priority, match=match,
                                    instructions=inst, idle_timeout=5)
        else:
            mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                    match=match, instructions=inst, idle_timeout=5)
        datapath.send_msg(mod)

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        """
        Handle packet in event.
        """
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        in_port = msg.match['in_port']

        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]

        if eth.ethertype == ether_types.ETH_TYPE_LLDP:
            # Ignore LLDP packet
            return

        dst = eth.dst
        src = eth.src

        dpid = datapath.id
        self.mac_to_port.setdefault(dpid, {})

        self.logger.info("Packet in %s %s %s %s", dpid, src, dst, in_port)

        # Learn a mac address to avoid FLOOD next time.
        self.mac_to_port[dpid][src] = in_port

        if dst in self.mac_to_port[dpid]:
            out_port = self.mac_to_port[dpid][dst]
        else:
            out_port = ofproto.OFPP_FLOOD

        actions = [parser.OFPActionOutput(out_port)]

        # Install a flow to avoid packet_in next time
        if out_port != ofproto.OFPP_FLOOD:
            match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
            self.add_flow1(datapath, 1, match, actions)

        data = None
        if msg.buffer_id == ofproto.OFP_NO_BUFFER:
            data = msg.data

        out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,
                                  in_port=in_port, actions=actions, data=data)
        datapath.send_msg(out)

        # Check if the packet is a TCP SYN packet
        ip_pkt = pkt.get_protocol(ipv4.ipv4)
        tcp_pkt = pkt.get_protocol(tcp.tcp)
        if ip_pkt and tcp_pkt and tcp_pkt.bits == tcp.TCP_SYN:
            self.logger.info("TCP SYN packet detected")
            # Redirect traffic to server2
            self.redirect_traffic(datapath, in_port, ip_pkt, tcp_pkt)

    def redirect_traffic(self, datapath, in_port, ip_pkt, tcp_pkt):
        """
        Redirect traffic to server2.
        """
        parser = datapath.ofproto_parser
        ofproto = datapath.ofproto

        # Create match for TCP SYN packet
        match = parser.OFPMatch(eth_type=ether_types.ETH_TYPE_IP,
                                ipv4_src=ip_pkt.src,
                                ipv4_dst=ip_pkt.dst,
                                ip_proto=ip_pkt.proto,
                                tcp_src=tcp_pkt.src_port,
                                tcp_dst=tcp_pkt.dst_port)

        # Create actions to redirect to server2
        actions = [parser.OFPActionSetField(eth_dst=server2['mac']),
                   parser.OFPActionSetField(ipv4_dst=server2['ip']),
                   parser.OFPActionOutput(ofproto.OFPP_IN_PORT)]

        # Install flow entry to redirect traffic
        self.add_flow1(datapath, 2, match, actions)

        # Send the TCP SYN packet out
        out = parser.OFPPacketOut(datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER,
                                  in_port=in_port, actions=actions, data=None)
        datapath.send_msg(out)
